import ServiceAPI from "../middleware/DataAcqusitionService";
import Auth from "../middleware/Auth";

import { FolderTask } from "../component/Uploader/core/types";

export const ParentOrigin = "http://localhost:9527";

// const checkAPI = {
//     origin: '/manager/origin/data/checkXmlInfo',
//     label: '/manager/label/data/checkJsonInfo',
//     evaluation: '/manager/evaluation/data/checkJsonInfo',
//     deepLearning: '/manager/deep/learning/data/set/checkJsonInfo',
//   };

export const addSource2Srv = (folderTask, resolve) => {
    const folderInfo = {
        fileFormat: Array.from(folderTask.fileFormat).join(","), //"idx,pdf,xml",
        fileName: folderTask.fileName.slice(1),
        fileSize: folderTask.fileSize,
        fileUrl: folderTask.fileName.slice(1),
        parentFolderName: "",
    };
    const config = {
        headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${Auth.GetDataAcquisitionPlatformToken(
                "token"
            )}`,
        },
        timeout: 5000,
    };
    const url = "/manager/origin/data";

    ServiceAPI.post(url, folderInfo, config).then((response) => {
        console.log("Response data:", response.data);
        if (response && response.data) {
            window.parent.postMessage(
                {
                    type: Auth.GetDataAcquisitionPlatformToken("type"),
                    packageName: folderTask.fileName.slice(1),
                    success: true,
                },
                ParentOrigin
            );
            resolve();
        } else {
            window.parent.postMessage(
                {
                    type: Auth.GetDataAcquisitionPlatformToken("type"),
                    packageName: folderTask.fileName.slice(1),
                    success: true,
                },
                ParentOrigin
            );
        }
    });
};
export const addAnnotation2Srv = (folderTask, resolve) => {
    // 标注数据集
    const base = folderTask.fileName.split("/").filter((item) => !!item);
    const fileUrl = base.join("/");
    const fileName = base[base.length - 1];

    const folderInfo = {
        fileFormat: Array.from(folderTask.fileFormat).join(","), //"idx,pdf,xml",
        id: folderTask.checkXmlJsonId,
        fileName: fileName,
        fileSize: folderTask.fileSize,
        fileUrl: fileUrl,
        fileNum: folderTask.fileNum,
        folderId: folderTask.folderId,
        fileNameList: folderTask.fileNameList,
        jsonFileNameList: folderTask.jsonFileNameList,
    };
    const config = {
        headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${Auth.GetDataAcquisitionPlatformToken(
                "token"
            )}`,
        },
        timeout: 5000,
    };
    const url = "/manager/label/data/saveLabelData";

    ServiceAPI.post(url, folderInfo, config).then((response) => {
        console.log("Response data:", response.data);
        if (response && response.data) {
            window.parent.postMessage(
                {
                    type: Auth.GetDataAcquisitionPlatformToken("type"),
                    packageName: folderTask.fileName.slice(1),
                    success: true,
                },
                ParentOrigin
            );
            resolve();
        }
    });
};
export const addEvaluation2Srv = (folderTask, resolve) => {
    const base = folderTask.fileName.split("/").filter((item) => !!item);
    const fileUrl = base.join("/");
    const fileName = base[base.length - 1];
    // 评测数据集
    const folderInfo = {
        fileFormat: Array.from(folderTask.fileFormat).join(","), //"idx,pdf,xml",
        id: folderTask.checkXmlJsonId,
        fileName: fileName,
        fileSize: folderTask.fileSize,
        fileNum: folderTask.fileNum,
        folderId: folderTask.folderId,
    };
    const config = {
        headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${Auth.GetDataAcquisitionPlatformToken(
                "token"
            )}`,
        },
        timeout: 5000,
    };
    const url = "/manager/evaluation/data";

    ServiceAPI.post(url, folderInfo, config).then((response) => {
        console.log("Response data:", response.data);
        if (response && response.data) {
            window.parent.postMessage(
                {
                    type: Auth.GetDataAcquisitionPlatformToken("type"),
                    packageName: folderTask.fileName.slice(1),
                    success: true,
                },
                ParentOrigin
            );
            resolve();
        }
    });
};
export const addSet2Srv = (folderTask, resolve) => {
    const base = folderTask.fileName.split("/").filter((item) => !!item);
    const fileUrl = base.join("/");
    const fileName = base[base.length - 1];
    // 深度学习数据集
    const folderInfo = {
        id: folderTask.checkXmlJsonId,
        fileName: fileName,
        fileSize: folderTask.fileSize,
        fileNum: folderTask.fileNum,
        folderId: folderTask.folderId,
        fileNameList: folderTask.fileNameList,
        jsonFileNameList:
            folderTask.jsonFileNameList &&
            folderTask.jsonFileNameList.length !== 0
                ? folderTask.jsonFileNameList
                : [],
    };
    const config = {
        headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${Auth.GetDataAcquisitionPlatformToken(
                "token"
            )}`,
        },
        timeout: 5000,
    };
    const url = "/manager/deep/learning/data/set";

    ServiceAPI.post(url, folderInfo, config).then((response) => {
        console.log("Response data:", response.data);
        if (response && response.data) {
            window.parent.postMessage(
                {
                    type: Auth.GetDataAcquisitionPlatformToken("type"),
                    packageName: folderTask.fileName.slice(1),
                    success: true,
                },
                ParentOrigin
            );
            resolve();
        }
    });
};
export const addMap2Srv = (folderTask, resolve) => {
    const base = folderTask.fileName.split("/").filter((item) => !!item);
    const fileUrl = base.join("/");
    const fileName = base[base.length - 1];
    // 地图数据集
    const folderInfo = {
        id: 0,
        // folderId: folderTask.folderId,
        fileName: fileName,
        fileSize: folderTask.fileSize,
        fileNum: folderTask.fileNum,
    };
    const config = {
        headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${Auth.GetDataAcquisitionPlatformToken(
                "token"
            )}`,
        },
        timeout: 5000,
    };
    const url = "/manager/map/origin/data";

    ServiceAPI.post(url, folderInfo, config).then((response) => {
        console.log("Response data:", response.data);
        if (response && response.data) {
            window.parent.postMessage(
                {
                    type: Auth.GetDataAcquisitionPlatformToken("type"),
                    packageName: folderTask.fileName.slice(1),
                    success: true,
                },
                ParentOrigin
            );
            resolve();
        }
    });
};
export const SiteConfig = {
    code: 0,
    data: {
        title: "Cloudreve",
        loginCaptcha: false,
        regCaptcha: false,
        forgetCaptcha: false,
        emailActive: false,
        themes: '{"#3f51b5":{"palette":{"primary":{"main":"#3f51b5"},"secondary":{"main":"#f50057"}}},"#2196f3":{"palette":{"primary":{"main":"#2196f3"},"secondary":{"main":"#FFC107"}}},"#673AB7":{"palette":{"primary":{"main":"#673AB7"},"secondary":{"main":"#2196F3"}}},"#E91E63":{"palette":{"primary":{"main":"#E91E63"},"secondary":{"main":"#42A5F5","contrastText":"#fff"}}},"#FF5722":{"palette":{"primary":{"main":"#FF5722"},"secondary":{"main":"#3F51B5"}}},"#FFC107":{"palette":{"primary":{"main":"#FFC107"},"secondary":{"main":"#26C6DA"}}},"#8BC34A":{"palette":{"primary":{"main":"#8BC34A","contrastText":"#fff"},"secondary":{"main":"#FF8A65","contrastText":"#fff"}}},"#009688":{"palette":{"primary":{"main":"#009688"},"secondary":{"main":"#4DD0E1","contrastText":"#fff"}}},"#607D8B":{"palette":{"primary":{"main":"#607D8B"},"secondary":{"main":"#F06292"}}},"#795548":{"palette":{"primary":{"main":"#795548"},"secondary":{"main":"#4CAF50","contrastText":"#fff"}}}}',
        defaultTheme: "#3f51b5",
        home_view_method: "icon",
        share_view_method: "list",
        authn: false,
        user: {
            id: "b3FM",
            user_name: "",
            nickname: "",
            status: 0,
            avatar: "",
            created_at: "0001-01-01T00:00:00Z",
            preferred_theme: "",
            anonymous: true,
            group: {
                id: 0,
                name: "Anonymous",
                allowShare: false,
                allowRemoteDownload: false,
                allowArchiveDownload: false,
                shareDownload: true,
                compress: false,
                webdav: false,
                sourceBatch: 0,
                advanceDelete: false,
                allowWebDAVProxy: false,
            },
            tags: [],
        },
        captcha_ReCaptchaKey: "defaultKey",
        captcha_type: "normal",
        tcaptcha_captcha_app_id: "",
        registerEnabled: true,
        app_promotion: true,
        wopi_exts: null,
        theme: {
            palette: {
                primary: { main: "#3f51b5" },
                secondary: { main: "#f50057" },
            },
        },
    },
    msg: "",
};

export const checkXmlJsonRequest = ({
    base,
    packageName,
    fileName,
    file,
    folderId,
    checkUrl,
}): Promise<{ type: boolean; id: string; folderKey: string; msg?: string }> => {
    /**
     * params:{
     *  file:(binary)
     *  base:前端测试
     *  folderld:1592345940695003138
     *  packageName:3DtuAng_test dataset min2
     *  fileName:前端测试/3DtuAng test dataset_min2
     * }
     */
    return new Promise((resolve, reject) => {
        if (!checkUrl) {
            return resolve({
                type: true,
                id: "",
                folderKey: fileName,
            });
        }
        const formdata = new FormData();
        if (checkUrl.includes("describe.xml")) {
            formdata.append(
                "file",
                new File([file], "describe.xml", { type: "text/xml" })
            );
        } else {
            formdata.append(
                "file",
                new File([file], "message.json", { type: "text/json" })
            );
        }

        if (folderId) {
            formdata.append("base", (file.base = base));
            formdata.append("folderId", (file.folderId = folderId));
            formdata.append("packageName", packageName);
        }
        formdata.append("fileName", fileName);
        ServiceAPI.post(checkUrl, formdata, {
            headers: {
                Authorization: `Bearer ${Auth.GetDataAcquisitionPlatformToken(
                    "token"
                )}`,
            },
        }).then((res) => {
            if (res.data && res.data.id) {
                // 标注
                resolve({
                    type: true,
                    id: res.data.id,
                    folderKey: fileName,
                });
            } else if (res.data && typeof res.data === "string") {
                // 评测/深度学习数据集
                resolve({
                    type: true,
                    id: res.data,
                    folderKey: fileName,
                });
            } else {
                resolve({
                    type: false,
                    // msg: res.msg,
                    id: res.data.id,
                    folderKey: fileName,
                });
            }
        });
    });
};
export const handleRequset = (folderTask): Promise<FolderTask> => {
    const type = Auth.GetDataAcquisitionPlatformToken("type");
    return new Promise((resolve, reject) => {
        if (type === "origin") {
            addSource2Srv(folderTask, resolve);
        } else if (type === "label") {
            addAnnotation2Srv(folderTask, resolve);
        } else if (type === "evaluation") {
            addEvaluation2Srv(folderTask, resolve);
        } else if (type === "deepLearning") {
            addSet2Srv(folderTask, resolve);
        } else if (type === "atlas") {
            addMap2Srv(folderTask, resolve);
        }
    });
};
